/**
 * http://blog.shiqichan.com/introducing-mqtt/
 * 这个模块已经不再维护了
 * 已经过时了，运行不成功
 * p
 */

var net     = require('net');
var mqttCon = require('mqtt-connection');
var  server  = new net.Server();

//定义一个订阅客户端队列
var subscribeTopics = {};

server.on('connection',function(stream){

    var server = mqttCon(stream);
    //建立连接时触发
    client.on('conncet',function(packet){
        client.connack({returnCode : 0});
        console.log('建立一个连接')
    });

    //客户端发布主题时触发
    client.on('publish',function(packet){
        
        //取得主题与
        var topic = packet.topic;      //主题
        var payload = packet.payload;  //消息内容

        //如果没有定义这个主题，创建主题对应的空client数组
        if(subscribeTopics[topic]==null){
            subscribeTopics[topic]=[];
        }else{
            //遍历主题下全部的client,并一个一个发送消息
            for(var i in subscribeTopics[topic]){
                var client =subscribeTopics[topic][i];
                client.publish({
                    topic : topic,
                    payload : payload
                });
            }
        }
    });

    //客户端订阅时触发
    client.on('subscribe',function(packet){
        var topic = packet.subscribeTopics[0].topic;
        console.log(topic);
        //如没有，创建空的主题对应的client数组
        if(subscribeTopics[topic] == null){
            subscribeTopics[topic] = [];
        }
        //如果client数组中没有当前client,加入
        if(subscribeTopics[topic].indexOf(client)== -1){
            subscribeTopics[topic].pub(client);
            console.log(client+' subscribe: '+topic);
        }
        console.log(subscribeTopics);
    });



    client.on('pingreq',function(packet){
        client.pingresp();
    });

    client.on('disconnect',function(packet){
        //遍历所有的主题，检查对应的数组中是否有当前client,从数组中删除
        for(var topic in subscribeTopics){
            var index = subscribeTopics[topic].indexOf(client);
            if(index >-1){
                subscribeTopics[topic].splice(index,1);
            }
        }
    });
});

server.listen(1883,function(){
    console.log('服务启动在1883端口')
})